package com.zhiyou100.javaweb.myservlet.homework.day004.studentmanagementsystem;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @packageName: javase_26
 * @className: ${NAME}
 * @Description: TODO 判断登陆页面
 * @author: yang
 * @date: 2020/5/25
 */
@WebServlet(name = "Day004ServletLogin", urlPatterns = "/day04/login")
public class Day004ServletLogin extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 1 设定编码集
        response.setContentType("text/html;charset=UTF-8");
        // 2 设定类型
        // 3 获取参数
        String name = request.getParameter("userName");
        String pwd = request.getParameter("userPwd");
        // 4 创建TeacherDao类
        TeacherDao teacherDao = new TeacherDao();
        // 5 判断登陆是否成功
        boolean login = teacherDao.isLogin(name, pwd);
        // 6 获取session
        HttpSession session = request.getSession();
        // 7 把登陆者的信息装入session域中，方便后面的资源获取
        session.setAttribute("teacher",new Teacher(name,pwd));
        if (login) {
            /*
             * 登陆成功处理
             * 获取方法
             * ServletContext context = request.getServletContext();
             * context=this.getServletConfig().getServletContext();
             * context=request.getSession().getServletContext();
             * context=this.getServletContext();
             * response.sendRedirect("http://localhost:1024/javase_26_war_exploded/day004/tool.html");
             * 请求转发给 /day004/tool.html
             */
            // 获取 Application域
            ServletContext servletContext = this.getServletContext();
            // 获取loginNumber属性
            Object logNumber = servletContext.getAttribute("loginNumber");
            if (logNumber==null){
                // 如果没有该属性，当前登陆者是第一个
                servletContext.setAttribute("loginNumber",1);
            }else {
                // 如果有，+1
                servletContext.setAttribute("loginNumber",(Integer)(logNumber)+1);
            }
            request.getRequestDispatcher("/day004/tool.html").forward(request,response);
        }else {
            // 登陆失败处理
            PrintWriter writer = response.getWriter();
            writer.write("登陆失败！");
            writer.flush();
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
